//
//  CreatNewAddressVC.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/27.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "CreatNewAddressVC.h"
#import "CreatAddressTopCell.h"
#import "CreatAddressTwoCell.h"
#import "CreatAddressSelectCell.h"
#import "CreatAddressLastCell.h"
#import "ZanWeiCell.h"
#import "CreatAddressLastView.h"
#import "BottomButtonView.h"

#import "ProvinceModel.h"

#import "CitysModel.h"

#import "DistrictsModel.h"

#import <LEEAlert/LEEAlert.h>
#import "AddressInfoModel.h"
#import "SelectedListModel.h"

#import "SelectedListView.h"
@interface CreatNewAddressVC ()
/** <#note#> */
@property (nonatomic, strong) CreatAddressLastView *headerView;

@property (nonatomic, strong) BottomButtonView *footerView;

@property (nonatomic, strong) NSMutableArray<NSDictionary *> *dateArray;


@end

@implementation CreatNewAddressVC

- (AddressInfoModel *)infoModel{
    
    if (!_infoModel) {
        _infoModel = [[AddressInfoModel alloc]init];
    }
    
    return _infoModel;
}




- (NSMutableArray<NSDictionary *> *)dateArray{
    
    if (_dateArray == nil) {
        
        _dateArray = [[NSMutableArray alloc]init];
        
        for (ProvinceModel *province in myViewModel.areas) {
            NSMutableDictionary *mutDictionary = [[NSMutableDictionary alloc]init];
            mutDictionary[@"name"] = province.province_name;
            NSMutableArray<NSMutableDictionary *> *tempArray = [[NSMutableArray alloc]init];
            
            for (CitysModel *city in province.citys) {
                NSMutableDictionary *subDictionary = [[NSMutableDictionary alloc]init];
                subDictionary[@"name"] = city.city_name;
                NSMutableArray *subArray = [[NSMutableArray alloc]init];
                
                for (DistrictsModel *district in city.districts) {
                    
                    [subArray addObject:district.district_name];

                }
                
                subDictionary[@"sub"] = subArray;
                
                [tempArray addObject:subDictionary];
            }
            
      
            mutDictionary[@"sub"] = tempArray;
            
            [_dateArray addObject:mutDictionary];
        }
        
  
        
    }
    
    
    return _dateArray;
    
}


- (CreatAddressLastView *)headerView{
    
    if (!_headerView) {
        
        CreatAddressLastView *temp = (CreatAddressLastView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CreatAddressLastView class]) owner:nil options:nil].firstObject;
        
        temp.frame = CGRectMake(KScreenW - 100, 0, 102, 100);
        
        temp.model = self.infoModel;
        
        _headerView = temp;
        
    }
    
    return _headerView;
}


- (BottomButtonView *)footerView{
    
    if (!_footerView) {
        
        BottomButtonView *temp = (BottomButtonView *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([BottomButtonView class]) owner:nil options:nil].firstObject;
        
        temp.frame = CGRectMake(0, 0, KScreenW, 160);
        
        [temp.btn addTarget:self action:@selector(saveAddressInfo) forControlEvents:UIControlEventTouchUpInside];
        
        _footerView = temp;
        
    }
    
    return _footerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"新增地址";

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.plainTableView.backgroundColor = [UIColor whiteColor];
    
    self.plainTableView.rowHeight = UITableViewAutomaticDimension;
    
    self.plainTableView.estimatedRowHeight = 100;
    
    self.plainTableView.tableFooterView = self.footerView;
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([CreatAddressTopCell class]) bundle:nil] forCellReuseIdentifier:[CreatAddressTopCell identifierStr]];
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([CreatAddressTwoCell class]) bundle:nil] forCellReuseIdentifier:[CreatAddressTwoCell identifierStr]];

    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([CreatAddressSelectCell class]) bundle:nil] forCellReuseIdentifier:[CreatAddressSelectCell identifierStr]];

    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([CreatAddressLastCell class]) bundle:nil] forCellReuseIdentifier:[CreatAddressLastCell identifierStr]];
    
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZanWeiCell class]) bundle:nil] forCellReuseIdentifier:[ZanWeiCell identifierStr]];
    
    
    
    [self.plainTableView addSubview:self.headerView];
    
    

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshPainTableView) name:@"DidSelectNameAndPhone" object:nil];
}

- (void)refreshPainTableView{
    
    [self.plainTableView reloadData];
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}




#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
      return  1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
         return  5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        CreatAddressTopCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[CreatAddressTopCell identifierStr]];
        
        tableCell.model = self.infoModel;
        
        return tableCell;
        
        
    } else if (indexPath.row == 1){
        
        CreatAddressTwoCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[CreatAddressTwoCell identifierStr]];
        
        tableCell.model = self.infoModel;

        return tableCell;
    }else if (indexPath.row == 2){
        
        CreatAddressSelectCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[CreatAddressSelectCell identifierStr]];
        
        tableCell.areaText = self.lastString;

        return tableCell;
    }else if (indexPath.row == 3){
        
        CreatAddressLastCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[CreatAddressLastCell identifierStr]];
        
        tableCell.tableView = self.plainTableView;
        
        tableCell.model = self.infoModel;

        return tableCell;
    }else{
        
        ZanWeiCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[ZanWeiCell identifierStr]];
        
        
        return tableCell;
    }
    
    
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    
    if (indexPath.row == 2) {
        
        [self selectAreas];
    }
    
    
}


- (void)processData{
    
    self.provinceId = nil;
    self.cityId = nil;
    self.districtId = nil;
    
    for (ProvinceModel *province in myViewModel.areas) {
        
        if ([province.province_name isEqualToString:self.province]) {
            
            self.provinceId = province.province_id;
            
            for (CitysModel *city in province.citys) {
                
                if ([city.city_name isEqualToString:self.city]){
                    self.cityId = city.city_id;
                    
                    for (DistrictsModel *district in city.districts) {
                        
                        if ([district.district_name isEqualToString:self.districts]) {
                            self.districtId = district.district_id;
                        }
                    }
                    
                }
                
            }
            
//            NSLog(@"%@===%@===%@",self.provinceId,self.cityId,self.districtId);
            return;
        }
        
        
        
    }
    
    
    
    
}

- (void)selectAreas{
    
    __block NSString *province = nil;
    
    __block NSString *city = nil;
    
    __block NSString *area = nil;
    
    
    MJWeakSelf;
    void (^resultBlock)(void) = ^{
        
        
        weakSelf.province = province;
        
        weakSelf.city = city;
        
        weakSelf.districts = area;
        
        if (area.length > 0) {
            
            weakSelf.lastString = [NSString stringWithFormat:@"%@-%@-%@",province,city,area];

        } else {
            weakSelf.lastString = [NSString stringWithFormat:@"%@-%@",province,city];

        }
        
        [weakSelf.plainTableView reloadData];
        
        
        [weakSelf processData];
        

        

    };
    
    
    NSArray *provinceArray = self.dateArray;
    
    if (provinceArray.count) {
        
        // 获取省数据 并显示
        
        NSMutableArray *array = [NSMutableArray array];
        
        [provinceArray enumerateObjectsUsingBlock:^(NSDictionary *info, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [array addObject:[[SelectedListModel alloc] initWithSid:idx Title:info[@"name"] Context:info]];
        }];
        
        SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
        
        view.isSingle = YES;
        
        view.array = array;
        
        view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
            
            [LEEAlert closeWithCompletionBlock:^{
                
                // 根据选中的省获取市数据 并显示
                
                SelectedListModel *model = array.firstObject;
                
                province = model.title; //设置省
                
                NSArray *cityArray = model.context[@"sub"];
                
                if (cityArray.count) {
                    
                    NSMutableArray *array = [NSMutableArray array];
                    
                    [cityArray enumerateObjectsUsingBlock:^(NSDictionary *info, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        [array addObject:[[SelectedListModel alloc] initWithSid:idx Title:info[@"name"] Context:info]];
                    }];
                    
                    SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
                    
                    view.isSingle = YES;
                    
                    view.array = array;
                    
                    view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
                        
                        [LEEAlert closeWithCompletionBlock:^{
                            
                            // 根据选中的市获取区数据 并显示
                            
                            SelectedListModel *model = array.firstObject;
                            
                            city = model.title; //设置市
                            
                            NSArray *areaArray = model.context[@"sub"];
                            
                            if (areaArray.count) {
                                
                                NSMutableArray *array = [NSMutableArray array];
                                
                                [areaArray enumerateObjectsUsingBlock:^(NSString *area, NSUInteger idx, BOOL * _Nonnull stop) {
                                    
                                    [array addObject:[[SelectedListModel alloc] initWithSid:idx Title:area]];
                                }];
                                
                                SelectedListView *view = [[SelectedListView alloc] initWithFrame:CGRectMake(0, 0, 280, 0) style:UITableViewStylePlain];
                                
                                view.isSingle = YES;
                                
                                view.array = array;
                                
                                view.selectedBlock = ^(NSArray<SelectedListModel *> *array) {
                                    
                                    [LEEAlert closeWithCompletionBlock:^{
                                        
                                        // 获取区数据 并显示最终结果
                                        
                                        SelectedListModel *model = array.firstObject;
                                        
                                        area = model.title; //设置区
                                        
                                        //                                                NSLog(@"%@----",area);
                                        
                                        
                                        if (resultBlock) resultBlock();
                                    }];
                                    
                                };
                                
                                [LEEAlert alert].config
                                .LeeTitle(model.title)
                                .LeeCustomView(view)
                                .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
                                .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
                                .LeeClickBackgroundClose(YES)
                                .LeeShow();
                                
                            } else {
                                
                                if (resultBlock) resultBlock();
                            }
                            
                        }];
                        
                    };
                    
                    [LEEAlert alert].config
                    .LeeTitle(model.title)
                    .LeeCustomView(view)
                    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
                    .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
                    .LeeClickBackgroundClose(YES)
                    .LeeShow();
                    
                } else {
                    
                    if (resultBlock) resultBlock();
                }
                
            }];
            
        };
        
        [LEEAlert alert].config
        .LeeTitle(@"请选择")
        .LeeCustomView(view)
        .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))
        .LeeHeaderInsets(UIEdgeInsetsMake(10, 0, 0, 0))
        .LeeClickBackgroundClose(YES)
        .LeeShow();
    }
    
}


- (void)saveAddressInfo{
    
    [self.view endEditing:YES];
    
    if (self.infoModel.consigner == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请填写收货人姓名"];
        
        return;
    }
    
    
    if (self.infoModel.mobile == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请填写收货人手机号"];
        
        return;
    }
    
    BOOL istelephoneNumber = [[NetworkTools shareNetworkTools] isPhoneNumber:self.infoModel.mobile];
    
    if (!istelephoneNumber) {
        
        [SVProgressHUD showInfoWithStatus:@"手机号格式不正确!"];
        
        return;
        
    }
    
    if (self.provinceId == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请选择所在区域"];
        
        return;
        
    }
    
    
    if (self.infoModel.address == nil) {
        
        [SVProgressHUD showInfoWithStatus:@"请填写详细地址"];
        
        return;
        
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"uid"] = myViewModel.user.uid;
    parameters[@"consigner"] = self.infoModel.consigner;
    parameters[@"mobile"] = self.infoModel.mobile;
    parameters[@"province"] = self.provinceId;
    parameters[@"city"] = self.cityId;
    parameters[@"district"] = self.districtId;
    parameters[@"address"] = self.infoModel.address;
    
    if (self.infoModel.addressID.length > 0) {
        
        parameters[@"id"] = self.infoModel.addressID;

    }

    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"Member/addMemberExpressAddress" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            MYJSONSTR
            
            [SVProgressHUD showSuccessWithStatus:responseObject[@"message"]];

            [[NSNotificationCenter defaultCenter]postNotificationName:@"AddressDidAdd" object:nil];
            
            
            [weakSelf.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:@1 afterDelay:2.0];

            
        } else {
            
            [SVProgressHUD showInfoWithStatus:error.domain];
        }
        
    }];
    
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self.view endEditing:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
